#include <cstdio>
#include <cstdlib>
#include "replace.h"

namespace  {
	const int totalCommandArguments = 5;
	const int inputFileArgumentIndex = 1;
	const int outputFileArgumentIndex = 2;
	const int whatReplaceArgumentIndex = 3;
	const int replacementArgumentIndex = 4;
}

void showUsage() {
	printf("Usage: program inputFile outputFile whatReplace replacement\n");
}

int main(int argc, char **argv) {

	if( ::totalCommandArguments != argc ) {
		showUsage();
		return EXIT_FAILURE;
	}
	 
	FILE *inputFile = NULL, *outputFile = NULL;
	if( 0 != fopen_s(&inputFile, argv[::inputFileArgumentIndex], "rb") ) {
		fprintf(stderr, "Error open input file\n");
		return EXIT_FAILURE;
	}

	if( 0 != fopen_s(&outputFile, argv[::outputFileArgumentIndex], "wb") ) {
		fprintf(stderr, "Error open output file\n");
		if ( EOF == fclose(inputFile)) {
			fprintf(stderr, "Error close output file\n");
			return EXIT_FAILURE;
		}
			return EXIT_FAILURE;
	}

	replace::replaceStrings(*inputFile, *outputFile, argv[::whatReplaceArgumentIndex], argv[::replacementArgumentIndex] );
	
	if( 0 != fclose(inputFile) ) {
		fprintf(stderr, "Error close input file\n");
		_fcloseall ();
		return EXIT_FAILURE;
	}

	if( 0 != fclose(outputFile) ) {
		fprintf(stderr, "Error close output file\n");
		return EXIT_FAILURE;
	}
	
	_fcloseall();
	return EXIT_SUCCESS;

}